package com.project.market.service.impl;

import com.project.market.db.domain.MarketSystem;
import com.project.market.db.domain.MarketSystemExample;
import com.project.market.db.mapper.MarketSystemMapper;
import com.project.market.service.AdminConfigService;
import com.project.market.util.JacksonUtil;
import com.project.market.util.MybatisUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.SqlSession;

import java.time.LocalDateTime;
import java.util.*;

public class AdminConfigServiceImpl implements AdminConfigService {

    /*
    请求方法为post的url
     */
    @Override
    public MarketSystem mall(Map<String,Object> map) {

        SqlSession session = MybatisUtil.getSession();
        MarketSystemMapper mapper = session.getMapper(MarketSystemMapper.class);


        Set<Map.Entry<String, Object>> entries = map.entrySet();
        MarketSystem ms = null;
        for (Map.Entry<String, Object> entry : entries) {
            MarketSystemExample example = new MarketSystemExample();
            MarketSystemExample.Criteria criteria = example.createCriteria();
            criteria.andKeyNameEqualTo(entry.getKey());
            ms = mapper.selectOneByExample(example);
            if(ms ==null){
                MarketSystem marketSystem = new MarketSystem();
                marketSystem.setKeyName(entry.getKey());
                marketSystem.setKeyValue((String) entry.getValue());
                marketSystem.setAddTime(LocalDateTime.now());
                marketSystem.setUpdateTime(LocalDateTime.now());
                marketSystem.setDeleted(false);
                mapper.insert(marketSystem);
            }else {
                ms.setKeyValue((String) entry.getValue());
                ms.setUpdateTime(LocalDateTime.now());
                mapper.updateByExample(ms,example);
            }
        }

        session.commit();
        session.close();

        return ms;
    }

    /*
    请求方法为get的url
     */
    @Override
    public Map<String, Object> getMall() {

        List<String> list = new ArrayList<>();
        list.add("market_mall_longitude");
        list.add("market_mall_latitude");
        list.add("market_mall_address");
        list.add("market_mall_qq");
        list.add("market_mall_phone");
        list.add("market_mall_name");

        SqlSession session = MybatisUtil.getSession();
        MarketSystemMapper mapper = session.getMapper(MarketSystemMapper.class);
        MarketSystemExample example = new MarketSystemExample();
        MarketSystemExample.Criteria criteria = example.createCriteria();
        criteria.andKeyNameIn(list);

        List<MarketSystem> marketSystems = mapper.selectByExample(example);

        Map<String,Object> map = new HashMap();
        for (MarketSystem marketSystem : marketSystems) {
            map.put(marketSystem.getKeyName(),marketSystem.getKeyValue());
        }

        session.commit();
        session.close();
        return map;
    }
}
